package config

import (
    "github.com/tietang/go-nacos"
    "github.com/tietang/props/kvs"
    "net/http"
    "strconv"
    "strings"
)

const (
    //GET/POST/DELETE
    ENDPOINT_CONFIGS = "/nacos/v1/cs/configs"
)

type NacosStringConfigClient struct {
    kvs.MapProperties
    Client *nacos.NacosClient
    name   string
}

func NewNacosStringConfigClient(servers string) *NacosStringConfigClient {
    c := &NacosStringConfigClient{}
    c.Client = nacos.NewNacosClient(servers)
    c.name = "Nacos:" + servers
    return c
}

//get /nacos/v1/cs/configs
func (c *NacosStringConfigClient) Get(req NacosConfigRequest) (string, error) {
    _, body, err := c.Client.Get(req.RequestGetEndpoint())
    return string(body), err
}

//POST /nacos/v1/cs/configs
func (c *NacosStringConfigClient) Publish(req NacosConfigRequest) bool {
    code, body, err := c.Client.Post(req.RequestPublishEndpoint(), "application/x-www-form-urlencoded", []byte(req.RequestPostFormData()))
    if err != nil {
        return false
    }
    if code == http.StatusOK {
        ok, err := strconv.ParseBool(strings.TrimSpace(string(body)))
        if err != nil {
            return false
        }
        return ok
    } else {
        return false
    }
}

//delete /nacos/v1/cs/configs
func (c *NacosStringConfigClient) Delete(req NacosConfigRequest) bool {
    code, body, err := c.Client.Delete(req.RequestGetEndpoint())
    if err != nil {
        return false
    }
    if code == http.StatusOK {
        ok, err := strconv.ParseBool(strings.TrimSpace(string(body)))
        if err != nil {
            return false
        }
        return ok
    } else {
        return false
    }
}

//POST /nacos/v1/cs/configs/listener
func (c *NacosStringConfigClient) Listen() {

}
